<template>
	<view class="py-outer-content">
		<view class="py-list-content">
			<u-tabs :list="tabsList" @click="handleTabsClick"></u-tabs>
		</view>
		<view class="py-list-content py-flow-content" v-if="formShow"
			:style="{height: windowHeight ? 'calc('+ windowHeight + ' - 10rpx - 10rpx - 44px - 5px)' : ''}">
			<view class="py-content" style="margin-bottom: 10rpx;">
				<!-- #ifdef H5 -->
				<component :is="currentComponent" ref="currentComponent"></component>
				<!-- #endif -->

				<!-- #ifdef MP-WEIXIN || APP-PLUS -->
				<!-- 使用APP需要在main.js进行配置，配置位置有注释标注 -->
				<!-- 由于微信不支持动态组件，需要在pages.json中两处进行配置，配置位置有注释标注 -->
				<!-- 新增组件，只需要修改组件名称和最后条件判断中实际路径即可，并且将v-if替换成v-else-if -->
				<!-- ref内容不能修改 -->
				<!-- 条件判断中要写详细文件路径，包含前缀@和后缀.vue -->
				<!-- v-if="'@/pages/py/test.vue' == currentComponentPath" -->
				<test ref="currentComponent" v-if="'@/pages/py/test.vue' == currentComponentPath"></test>
				<!-- #endif -->
			</view>
			<u-line></u-line>
			<view style="margin: 5rpx 0 5rpx 0;">
				<u-row justify="center" :gutter="3">
					<u-col :span="3">
						<u-button type="primary" text="保存" @click="submitForm(false)"></u-button>
					</u-col>
					<u-col :span="3">
						<u-button type="success" text="发起" @click="submitForm(true)"></u-button>
					</u-col>
					<u-col :span="3">
						<u-button type="info" text="重置" @click="resetForm"></u-button>
					</u-col>

				</u-row>

			</view>

		</view>
		<view class="py-flow-content" v-else-if="flowableShow"
			:style="{height: windowHeight ? 'calc('+ windowHeight + ' - 10rpx - 44px - 5px)' : ''}">
			<py-bpmn-viewer :flowData="flowData" :hasStart="false"></py-bpmn-viewer>
		</view>



	</view>

</template>
<script>
	import {
		getFlowableForm
	} from "@/api/flowable/flowableForm";
	import {
		getNextFlowNodeByStart
	} from "@/api/flowable/todo";
	import {
		definitionStart,
		flowXmlAndNode
	} from "@/api/flowable/definition";
	import {
		getWindowHeight,
		getVarType
	} from "@/utils/py";
	export default {
		data() {
			return {
				// 标签列表信息
				tabsList: [{
					name: "表单信息"
				},
				{
					name: "流程图"
				}
				],
				// 是否展示表单信息
				formShow: true,
				// 是否展示流程图
				flowableShow: false,

				// 模型xml数据
				flowData: {},
				// 查询参数
				queryParams: {
					deptId: undefined
				},
				deployId: "", // 流程定义编号
				procDefId: "", // 流程实例编号

				// 当前组件
				// #ifdef APP-PLUS || H5
				currentComponent: undefined,
				// #endif

				// #ifdef APP-PLUS
				// App组件路径
				currentAppComponentPath: "",
				// #endif

				// 表单Id
				formId: undefined,

				// 是否启动流程
				hasStart: false,

				// 窗口高度（去掉导航栏）
				windowHeight: undefined,

				// 当前组件路径
				// #ifdef MP-WEIXIN || APP-PLUS
				currentComponentPath: "",
				// #endif

				// 是否启动流程
				hasStart: false

			}
		},
		onLoad: function (options) {
			if (options) {
				this.deployId = options.deployId;
				this.procDefId = options.procDefId;
				this.formId = options.formId;
			}

			// 获取窗口高度
			this.getWindowHeight();

			if (this.formId == undefined || this.formId == null || this.formId == "null") {
				this.$modal.msgError("流程没有配置表单，无法启动");
				return;
			}
			this.getFlowFormData(this.formId);

			// 监听保存表单
			uni.$once('saveForm', form => {
				this.saveForm(form);
			})

		},
		methods: {

			// 获取窗口高度
			getWindowHeight() {
				getWindowHeight().then(response => {
					this.windowHeight = response;
				})
			},

			// 处理标签点击操作
			handleTabsClick(item) {
				let index = item && item.index;
				switch (index) {
					case 0:
						this.flowableShow = false;
						this.formShow = true;
						break;
					case 1:
						// 获取流程图xml
						this.getFlowableXml();
						break;
				}
			},

			// 获取流程图Xml
			getFlowableXml() {
				flowXmlAndNode({
					procInsId: this.procInsId,
					deployId: this.deployId
				}).then(res => {
					this.formShow = false;
					this.flowableShow = true;
					this.flowData = res.data;
				})
			},

			// 导入组件
			importComponent(componentPath) {
				if (!componentPath) {
					return;
				}
				let prefixIndex = componentPath.indexOf("@/");
				let suffixIndex = componentPath.lastIndexOf(".vue");
				if (prefixIndex == -1) {
					prefixIndex = 0;
				} else {
					prefixIndex = 2;
				}
				if (suffixIndex == -1) {
					suffixIndex = componentPath.length;
				}

				let path = componentPath.substring(prefixIndex, suffixIndex);
				let appPath = path.replace("views/", "pages/");

				// #ifdef H5
				this.currentComponent = resolve => require([`@/${appPath}.vue`], resolve);
				// #endif

				// #ifdef MP-WEIXIN || APP-PLUS
				this.currentComponentPath = `@/${appPath}.vue`;
				// #endif

			},

			/** 流程表单数据 */
			getFlowFormData(formId) {
				getFlowableForm(formId).then(response => {
					let data = response.data;
					this.importComponent(data.formPath);
				})
			},

			/** 重置表单 */
			resetForm() {
				this.$modal.confirm("确定重置填写信息？").then(() => {
					this.$refs.currentComponent.reset();
				})
			},

			// 显示成功信息，并且返回页面
			showSuccessMessageAndGoBack(message) {
				let delayTime = 1000;
				// 返回上层页面
				this.$modal.msgSuccess(message);
				// #ifdef MP-WEIXIN || APP-PLUS
				delayTime = 500;
				// #endif
				// 设置延迟，防止提示信息不显示
				setTimeout(() => {
					// this.$tab.redirectTo("/pages/flowable/myProcess/index");
					this.$tab.switchTab("/pages/work/index");
				}, delayTime);
			},

			/** 申请流程表单数据提交 */
			submitForm(hasStart) {
				this.hasStart = hasStart;
				this.$refs.currentComponent.submitForm();
			},

			// 保存表单
			saveForm(form) {
				let itemList = [];
				for (const key in form) {
					if (Object.hasOwnProperty.call(form, key)) {
						let eachObj = {};
						const element = form[key];
						eachObj["name"] = key;
						eachObj["type"] = getVarType(element);
						if (eachObj["type"] == "array") {
							eachObj["value"] = JSON.stringify(element);
						} else {
							eachObj["value"] = element;
						}
						itemList.push(eachObj);
					}
				}
				getNextFlowNodeByStart({ deploymentId: this.deployId }).then(res => {
					const data = res.data;
					if (data) {
						if (this.procDefId) {
							const param = {
								hasStart: this.hasStart
							}
							param["itemList"] = itemList;
							// 启动流程并将表单数据加入流程变量
							definitionStart(this.procDefId, param).then(response => {
								// 显示成功信息，并且返回页面
								this.showSuccessMessageAndGoBack(response.msg);
							})
						}
					}
				})

			},

		},
	}
</script>

<style lang="css" scoped>
	.py-flow-content {
		overflow: auto;
	}
</style>